package org.example.NetWork;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * @className: UdpEchoClient
 * @author: 芃
 * @description:
 * @date: 2024/5/10 17:55
 */
public class UdpEchoClient {
    private DatagramSocket socket = null;
    private String serverIP;
    private int serverPort;

    public UdpEchoClient(String ip, int port) throws SocketException {
        this.socket = new DatagramSocket();
        this.serverIP = ip;
        this.serverPort = port;
    }

    public void start() throws IOException {
        while(true) {
            Scanner scanner = new Scanner(System.in);
            System.out.print("-> ");
            String request = scanner.next();
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(), request.getBytes(StandardCharsets.UTF_8).length, InetAddress.getByName(this.serverIP), this.serverPort);
            this.socket.send(requestPacket);
            DatagramPacket responsePacket = new DatagramPacket(new byte[1024], 1024);
            this.socket.receive(responsePacket);
            String response = new String(responsePacket.getData(), 0, responsePacket.getLength());
            System.out.printf("req: %s,resp: %s\n", request, response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient client = new UdpEchoClient("127.0.0.1", 9090);
        client.start();
    }
}
